package com.cw.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.common.api.ResultObject;
import com.cw.constant.Constants;
import com.cw.dto.*;
import com.cw.entity.*;
import com.cw.mapper.CwglBedtypechangeMapper;
import com.cw.mapper2.*;
import com.cw.mapper3.LJysqdxxMapper;
import com.cw.request.*;
import com.cw.response.DataSourceResponse;
import com.cw.service.*;
import com.cw.util.HttpUtil;
import com.cw.util.PageHelperTool;
import com.cw.util.StringUtil;
import com.cw.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 住院预约表 服务实现类
 * </p>
 *
 * @author smq
 * @since 2021-05-06
 */
@Service
public class ThisIiPrepayinServiceImpl extends ServiceImpl<ThisIiPrepayinMapper, ThisIiPrepayin> implements IThisIiPrepayinService {


    @Autowired
    private BaseDict2Mapper baseDict2Mapper;

    @Autowired
    private ThisIiPrepayinMapper thisIiPrepayinMapper;

    @Autowired
    private CwglBedtypechangeMapper bedtypechangeMapper;


    @Autowired
    private PatientBedMiddleMapper patientBedMiddleMapper;

    @Autowired
    private ICwglBedtypechangeService bedTypeMapper;

    @Autowired
    private IVYqBrdjxxServiceImpl ivYqBrdjxxService;

    @Autowired
    private ILJysqdxxXmmxService ilJysqdxxXmmxService;

    @Autowired
    private ILJytmxxService ilJytmxxService;

    @Autowired
    private LJysqdxxMapper lJysqdxxMapper;

    @Autowired
    private IaSickbedinfoMapper iaSickbedinfoMapper;

    @Autowired
    private HisCwglDeptMapper deptMapper;

    @Autowired
    private HisCwglNurseMapper nurseMapper;

    /**
     * 住院登记记录-未登记
     *
     * @param condition 查询条件
     * @return com.github.pagehelper.PageInfo<com.cw.entity.ThisIiPrepayin>
     * @author ly
     * @date 2021/5/6 9:58
     */
    @Override
    public Map<String, Object> getThisIiPrepayinPagination(InpatientRegistrationCondition condition) {
        Map<String, Object> resultMap = new HashMap<>(2);
        //未预约计数
        List<NoAppointmentVO> noAppointmentVOList = new ArrayList<>();
        String stayInBed = condition.getStayInBed();
        if (!"1".equals(stayInBed)) {
            condition.setStayInBed(null);
        }
        //门诊
        Integer nullPorint = condition.getOutpatientPageNum();
        if (ObjectUtil.isNotNull(nullPorint)) {
            condition.setCode("1");
            //PageHelper.startPage(nullPorint, 15, false);
            // 获取所有 门诊 患者
            List<ThisIiPrepayin> thisIiPrepayins = baseMapper.getThisIiPrepayins(condition);
            // 院前患者
            List<ThisIiPrepayin> yqList = thisIiPrepayins.stream()
                    .filter(t -> t.getPatientTag() != null && t.getPatientTag().equals("2"))
                    .collect(Collectors.toList());
            List<BigDecimal> preList = yqList.stream().map(ThisIiPrepayin::getPreid).collect(Collectors.toList());
            // 获取所有普通患者
            List<ThisIiPrepayin> normalList = thisIiPrepayins.stream()
                    .filter(t -> !preList.contains(t.getPreid()))
                    .collect(Collectors.toList());
            List<ThisIiPrepayin> yQFinishYQPatient = new ArrayList<>();
            NoAppointmentVO noAppointmentVO = new NoAppointmentVO();
            //院前患者
            yQFinishYQPatient.addAll(yqList);
            //普通患者
            yQFinishYQPatient.addAll(normalList);
            //未预约计数
            int size = yQFinishYQPatient.size();
            noAppointmentVO.setType("门诊未安排");
            noAppointmentVO.setValue(size + "位");
            noAppointmentVOList.add(noAppointmentVO);
            resultMap.put("outpatient", yQFinishYQPatient);
            /**区分院前患者检查已完成 start
             // 获取院前患者的preId
             // 过滤院前所有检查完成的患者
             // 1 获取全部完成检查的患者
             List<ThisIiPrepayin> yqFinishList = getFinishYQ(yqList).stream().sorted(Comparator.comparing
             (ThisIiPrepayin::getPredate)).collect(Collectors.toList());
             // 2 获取全部完成检查的患者的preId
             List<BigDecimal> preyqFinishList = yqFinishList.stream().map(t -> t.getPreid()).collect(Collectors
             .toList());
             // 3 获取没有做完检查的患者
             List<ThisIiPrepayin> NoYqFinish = yqList.stream().filter(t -> !preyqFinishList.contains(t.getPreid()))
             .collect(Collectors.toList());
             NoYqFinish.forEach(item -> {
             //将未完成检查/检验的院前患者视为普通患者
             item.setPatientTag("0");
             });
             //new一个list
             List<ThisIiPrepayin> YQFinishYQPatient = new ArrayList<>();
             //院前完成检查的人
             YQFinishYQPatient.addAll(yqFinishList);
             //院前没有完成检查的
             YQFinishYQPatient.addAll(NoYqFinish);
             //普通患者
             YQFinishYQPatient.addAll(normalList);
             resultMap.put("outpatient", YQFinishYQPatient);
             **/
        }
        //急诊
        Integer nullPointCheck = condition.getEmergencyCallPageNum();
        if (ObjectUtil.isNotNull(nullPointCheck)) {
            condition.setCode("2");
            PageHelper.startPage(nullPointCheck, 15, false);
            List<ThisIiPrepayin> thisIiPrepayins = baseMapper.getThisIiPrepayins(condition);
            thisIiPrepayins = thisIiPrepayins.stream()
                    .sorted(Comparator.comparing(ThisIiPrepayin::getPredate).reversed())
                    .collect(Collectors.toList());
            //未预约计数
            NoAppointmentVO noAppointmentVO = new NoAppointmentVO();
            int size = thisIiPrepayins.size();
            noAppointmentVO.setType("急诊未安排");
            noAppointmentVO.setValue(size + "位");
            noAppointmentVOList.add(noAppointmentVO);
            resultMap.put("emergencyCall", thisIiPrepayins);
        }
        resultMap.put("noAppointment", noAppointmentVOList);
        return resultMap;
    }

    /**
     * 获取没有床位的患者信息
     *
     * @param eemptyPatientRequest
     * @return
     */

    @Override
    public PageInfo<ThisIiPrepayin> getEemptyPatientListNew(EemptyPatientRequest eemptyPatientRequest) {
        //默认查一个星期的数据
        if (!eemptyPatientRequest.getIsAll()) {
            //前一个星期的时间
            SimpleDateFormat dateformats = new SimpleDateFormat("yyyy-MM-dd");
            String dateStq = dateformats.format(System.currentTimeMillis());
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(Convert.toDate(dateStq));
            rightNow.add(Calendar.DATE, 1);
            eemptyPatientRequest.setEndDate(dateformats.format(rightNow.getTime()));
            rightNow.add(Calendar.DATE, -7);
            eemptyPatientRequest.setStartDate(dateformats.format(rightNow.getTime()));
        }
        List<ThisIiPrepayin> patientInfoList = thisIiPrepayinMapper.getEemptyPatientListNew(eemptyPatientRequest);
        int curentyear = Calendar.getInstance().get(Calendar.YEAR);
        patientInfoList.forEach(item -> {
            int birthday = 0;
            if (item.getBirthday() != null) {
                birthday = item.getBirthday().getYear();
            }
            String age = String.valueOf(curentyear - birthday);
            item.setAge(age);
        });
        return getFilterYQHZ(eemptyPatientRequest, patientInfoList);

    }

    @Override
    public PageInfo<ThisIiPrepayin> getEemptyPatientListAll(EemptyPatientRequest eemptyPatientRequest) {
        List<ThisIiPrepayin> patientInfoList = thisIiPrepayinMapper.getEemptyPatientListNew(eemptyPatientRequest);
        int curentyear = Calendar.getInstance().get(Calendar.YEAR);
        patientInfoList.forEach(item -> {
            int birthday = 0;
            if (item.getBirthday() != null) {
                birthday = item.getBirthday().getYear();
            }

            String age = String.valueOf(curentyear - birthday);
            item.setAge(age);
        });
        int pageIndex = eemptyPatientRequest.getPageNum();
        int pageSize = 20;
        return PageHelperTool.excutePageInfo(patientInfoList, pageIndex, pageSize);

    }

    /**
     * 当页面点击查看详细，和查看详细页面查询时不过滤院前患者，查询全部患者
     *
     * @param eemptyPatientRequest
     * @return
     */

    private PageInfo<ThisIiPrepayin> getFilterYQHZ(EemptyPatientRequest eemptyPatientRequest,
                                                   List<ThisIiPrepayin> patientInfoList) {
        //院前患者
        List<ThisIiPrepayin> yqList = patientInfoList.stream()
                .filter(t -> t.getPatientTag() != null && t.getPatientTag().equals("2"))
                .collect(Collectors.toList());
        //普通患者
        List<ThisIiPrepayin> normalList = patientInfoList.stream()
                .filter(t -> t.getPatientTag() == null || t.getPatientTag().equals("0"))
                .collect(Collectors.toList());
        //过滤院前所有检查完成的患者
        List<ThisIiPrepayin> yqFinishList = getFinishYQ(yqList);
        List<ThisIiPrepayin> newPatientInfoList = new ArrayList<>();
        newPatientInfoList.addAll(yqFinishList);
        newPatientInfoList.addAll(normalList);
        int pageIndex = eemptyPatientRequest.getPageNum();
        int pageSize = 10;
        return PageHelperTool.excutePageInfo(newPatientInfoList, pageIndex, pageSize);
    }

    /**
     * 手工录入
     *
     * @param prepayinDTO 手工录入信息
     * @return boolean
     * @author ly
     * @date 2021/5/13 16:04
     */
    @Override
    @Transactional
    public ResultObject insertIiPrepayin(PrepayinDTO prepayinDTO) throws Exception {
        //1-22
        ThisIiPrepayin thisIiPrepayin = new ThisIiPrepayin();
        //多余字段，用来存医保选项，用于编辑回显
        thisIiPrepayin.setMemo(prepayinDTO.getPaykindCode());
        //医保类型特殊处理
        if (prepayinDTO.getPaykindCode().contains("ZF")) {
            prepayinDTO.setPaykindCode(Constants.ZF);
        } else if (prepayinDTO.getPaykindCode().contains("YB")) {
            prepayinDTO.setPaykindCode(Constants.YB);
        }
        
        //工号
        String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
        if (!prepayinDTO.getOperCode().isEmpty()) {
            userName = prepayinDTO.getOperCode();
        }


        //add by cww 2021/09/14
        //这里主键特殊处理,床位管理系统Preid暂定从-1~-10000000 负一千万,防止多个系统的主键冲突(之前已存在的记录不管)
        BigDecimal minPreid = new BigDecimal(0);
        List<ThisIiPrepayin> minList = baseMapper.getMinPreId();
        if (!CollectionUtils.isEmpty(minList)) {
            minPreid = minList.get(0).getPreid();
            if (minPreid.equals(new BigDecimal(-10000000))) {
                return ResultObject.errorReturn("系统ID已达到上限,请联系管理员!");
            }
        }

        BigDecimal newPreid = minPreid.add(new BigDecimal(-1));

        //这一行在copy对象与对象 相同的类型 相同的变量名然后set进去,这里为什么要重新创建一个对象?
        //因为我要理清楚这里需要那些字段insert进去,Iiprepayin对象太乱了
        thisIiPrepayin.setPreid(newPreid);
        BeanUtil.copyProperties(prepayinDTO, thisIiPrepayin);
        thisIiPrepayin.setIdenno(prepayinDTO.getIdenNo());
        thisIiPrepayin.setOperCode(userName);
        thisIiPrepayin.setOperDtime(LocalDateTime.now());
        thisIiPrepayin.setPredate(prepayinDTO.getPreDate());
        thisIiPrepayin.setIfInhosExternal(prepayinDTO.getIfInhosExternal());

        Map<String, Object> resultMap = new HashMap<>(16);
        //当自费的时候 mcardNo医疗证号 空字符串 合同编码为0
        if ("01".equals(thisIiPrepayin.getPaykindCode())) {
            thisIiPrepayin.setMcardNo("");
            thisIiPrepayin.setPactCode("0");
            resultMap.put("pactCode", "0");
        } else if ("02".equals(thisIiPrepayin.getPaykindCode())) {
            thisIiPrepayin.setPactCode("99");
            resultMap.put("pactCode", "99");
        }
        DateTimeFormatter dataFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        resultMap.put("name", thisIiPrepayin.getName());
        resultMap.put("birthday", dataFormat.format(thisIiPrepayin.getBirthday()));
        resultMap.put("sex", thisIiPrepayin.getSex());
        resultMap.put("idenno", thisIiPrepayin.getIdenno());
        resultMap.put("home", thisIiPrepayin.getHome());
        resultMap.put("homeTel", thisIiPrepayin.getHomeTel());
        resultMap.put("paykindCode", thisIiPrepayin.getPaykindCode());
        resultMap.put("operCode", thisIiPrepayin.getOperCode());
        //医疗证号
        if (StringUtil.isNotEmpty(prepayinDTO.getMcardNo())) {
            resultMap.put("mcardNo", prepayinDTO.getMcardNo());
        } else {
            resultMap.put("mcardNo", null);
        }

        //职业编码
        if (prepayinDTO.getProfCode() != null) {
            //前端没有传递值,默认R8。
            if (StringUtil.isNotEmpty(prepayinDTO.getProfCode())) {
                resultMap.put("profCode", prepayinDTO.getProfCode());
            } else {
                resultMap.put("profCode", "R8");
            }
        } else {
            resultMap.put("profCode", "R8");
        }
        resultMap.put("result_code", "");
        resultMap.put("result_msg", "");
        resultMap.put("po_card_no", "");
//        resultMap.put("mszd",prepayinDTO.getMszd());
        //获取cardNo通过医院的存储过程
        baseDict2Mapper.getCardNo(resultMap);
        //0：建档成功；-1：建档失败；-2：建档失败，身份证存在，电话号码不一致，需要线下处理。
        String resultCode = resultMap.get("result_code").toString();
        switch (resultCode) {
            case "-1":
            case "-2":
                return ResultObject.errorReturn(resultMap.get("result_msg").toString());
            default:
                break;
        }
        //cardNo
        String cardNo = resultMap.get("po_card_no").toString();
        thisIiPrepayin.setCardNo(cardNo);
        thisIiPrepayin.setPreState("1");
        thisIiPrepayin.setIsManual("1");
        thisIiPrepayin.setDiagCode2(prepayinDTO.getDiagCode2());
        thisIiPrepayin.setDiagName2(prepayinDTO.getDiagName2() == null ? "" : prepayinDTO.getDiagName2());
        thisIiPrepayin.setDiagCode3(prepayinDTO.getDiagCode3());
        thisIiPrepayin.setDiagName3(prepayinDTO.getDiagName3() == null ? "" : prepayinDTO.getDiagName3());
        //预手术编码
        thisIiPrepayin.setPreOpcode(prepayinDTO.getPreOpcode() == null ? "" : prepayinDTO.getPreOpcode());
        //预手术名称
        thisIiPrepayin.setPreOpname(prepayinDTO.getPreOpname() == null ? "" : prepayinDTO.getPreOpname());
        //预手术级别
        thisIiPrepayin.setPreOpclass(prepayinDTO.getPreOpclass() == null ? "" : prepayinDTO.getPreOpclass());
        //是否为新技术
        thisIiPrepayin.setYnNewtech(prepayinDTO.getYnNewtech() == null ? "" : prepayinDTO.getYnNewtech());
        //是否跨科收治
        thisIiPrepayin.setYnOtherward(prepayinDTO.getYnOtherward() == null ? "" : prepayinDTO.getYnOtherward());
        //意向床位编码
        thisIiPrepayin.setBednoWangted(prepayinDTO.getBednoWangted() == null ? "" : prepayinDTO.getBednoWangted());
        //专业组编码
        thisIiPrepayin.setMedicalGroupCode(prepayinDTO.getMedicalGroupCode() == null ? "" : prepayinDTO.getMedicalGroupCode());
        //专业组名称
        thisIiPrepayin.setMedicalGroupName(prepayinDTO.getMedicalGroupName() == null ? "" : prepayinDTO.getMedicalGroupName());
        //医疗组组长编码
        thisIiPrepayin.setMedicalGroupLeaderCode(prepayinDTO.getMedicalGroupLeaderCode() == null ? "" : prepayinDTO.getMedicalGroupLeaderCode());
        //医疗组组长名称
        thisIiPrepayin.setMedicalGroupLeaderName(prepayinDTO.getMedicalGroupLeaderName() == null ? "" : prepayinDTO.getMedicalGroupLeaderName());
        boolean b = baseMapper.insertThisIiPrepayin(thisIiPrepayin);
        if (!b) {
            throw new Exception("保存失败");
        }
        return ResultObject.successReturn("录入成功!");
    }

    /**
     * 编辑-手工录入
     *
     * @param prepayinDTO 编辑对象
     * @return com.cw.common.api.ResultObject
     * @author ly
     * @date 2021/5/27 11:11
     */
    @Override
    @Transactional
    public ResultObject editIiPrepayin(PrepayinDTO prepayinDTO) {
        ThisIiPrepayin thisIiPrepayin = new ThisIiPrepayin();
        //多余字段，用来存医保选项，用于编辑回显
        thisIiPrepayin.setMemo(prepayinDTO.getPaykindCode());
        //医保类型特殊处理
        if (prepayinDTO.getPaykindCode().contains("ZF")) {
            prepayinDTO.setPaykindCode(Constants.ZF);
        } else if (prepayinDTO.getPaykindCode().contains("YB")) {
            prepayinDTO.setPaykindCode(Constants.YB);
        }
        //11-28
        String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
        if (prepayinDTO.getOperCode()!=null &&!prepayinDTO.getOperCode().isEmpty()) {
            userName = prepayinDTO.getOperCode();
        }
        BeanUtil.copyProperties(prepayinDTO, thisIiPrepayin);
        thisIiPrepayin.setOperCode(userName);
        thisIiPrepayin.setOperDtime(LocalDateTime.now());
        thisIiPrepayin.setPreid(BigDecimal.valueOf(prepayinDTO.getPreId()));
        thisIiPrepayin.setIdenno(prepayinDTO.getIdenNo());
        thisIiPrepayin.setPredate(prepayinDTO.getPreDate());
        thisIiPrepayin.setIfInhosExternal(prepayinDTO.getIfInhosExternal());

        Map<String, Object> resultMap = new HashMap<>();
        //当自费的时候 mcardNo医疗证号 空字符串 合同编码为0
        if ("01".equals(thisIiPrepayin.getPaykindCode())) {
            thisIiPrepayin.setMcardNo("");
            thisIiPrepayin.setPactCode("0");
            resultMap.put("pactCode", "0");
        } else if ("02".equals(thisIiPrepayin.getPaykindCode())) {
            thisIiPrepayin.setPactCode("99");
            resultMap.put("pactCode", "99");
        }
        DateTimeFormatter dataFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        resultMap.put("name", thisIiPrepayin.getName());
        resultMap.put("birthday", dataFormat.format(thisIiPrepayin.getBirthday()));
        resultMap.put("sex", thisIiPrepayin.getSex());
        resultMap.put("idenno", thisIiPrepayin.getIdenno());
        resultMap.put("home", thisIiPrepayin.getHome());
        resultMap.put("homeTel", thisIiPrepayin.getHomeTel());
        resultMap.put("paykindCode", thisIiPrepayin.getPaykindCode());
        resultMap.put("operCode", thisIiPrepayin.getOperCode());
        //医疗证号
        if (StringUtil.isNotEmpty(prepayinDTO.getMcardNo())) {
            resultMap.put("mcardNo", prepayinDTO.getMcardNo());
        } else {
            resultMap.put("mcardNo", null);
        }

        //职业编码
        if (prepayinDTO.getProfCode() != null) {
            if (StringUtil.isNotEmpty(prepayinDTO.getProfCode())) {
                resultMap.put("profCode", prepayinDTO.getProfCode());
            } else {
                resultMap.put("profCode", "R8");
            }
        } else {
            resultMap.put("profCode", "R8");
        }
        resultMap.put("result_code", "");
        resultMap.put("result_msg", "");
        resultMap.put("po_card_no", "");

        //获取cardNo通过医院的存储过程
        baseDict2Mapper.getCardNo(resultMap);
        //0：建档成功；-1：建档失败；-2：建档失败，身份证存在，电话号码不一致，需要线下处理。
        String resultCode = resultMap.get("result_code").toString();
        switch (resultCode) {
            case "-1":
            case "-2":
                return ResultObject.errorReturn(resultMap.get("result_msg").toString());
            default:
                break;
        }

        //cardNo
        String cardNo = resultMap.get("po_card_no").toString();
        thisIiPrepayin.setCardNo(cardNo);
//        thisIiPrepayin.setPreState("1");//这边有问题
        thisIiPrepayin.setPreState(prepayinDTO.getPreState());
        thisIiPrepayin.setIsManual("1");
        thisIiPrepayin.setDiagCode2(prepayinDTO.getDiagCode2() == null ? "" : prepayinDTO.getDiagCode2());
        thisIiPrepayin.setDiagName2(prepayinDTO.getDiagName2() == null ? "" : prepayinDTO.getDiagName2());
        thisIiPrepayin.setDiagCode3(prepayinDTO.getDiagCode3() == null ? "" : prepayinDTO.getDiagCode3());
        thisIiPrepayin.setDiagName3(prepayinDTO.getDiagName3() == null ? "" : prepayinDTO.getDiagName3());
        //预手术编码
        thisIiPrepayin.setPreOpcode(prepayinDTO.getPreOpcode() == null ? "" : prepayinDTO.getPreOpcode());
        //预手术名称
        thisIiPrepayin.setPreOpname(prepayinDTO.getPreOpname() == null ? "" : prepayinDTO.getPreOpname());
        //预手术级别
        thisIiPrepayin.setPreOpclass(prepayinDTO.getPreOpclass() == null ? "" : prepayinDTO.getPreOpclass());
        //是否为新技术
        thisIiPrepayin.setYnNewtech(prepayinDTO.getYnNewtech() == null ? "" : prepayinDTO.getYnNewtech());
        //是否跨科收治
        thisIiPrepayin.setYnOtherward(prepayinDTO.getYnOtherward() == null ? "" : prepayinDTO.getYnOtherward());
        //意向床位编码
        thisIiPrepayin.setBednoWangted(prepayinDTO.getBednoWangted() == null ? "" : prepayinDTO.getBednoWangted());
        //专业组编码
        thisIiPrepayin.setMedicalGroupCode(prepayinDTO.getMedicalGroupCode() == null ? "" : prepayinDTO.getMedicalGroupCode());
        //专业组名称
        thisIiPrepayin.setMedicalGroupName(prepayinDTO.getMedicalGroupName() == null ? "" : prepayinDTO.getMedicalGroupName());
        //医疗组组长编码
        thisIiPrepayin.setMedicalGroupLeaderCode(prepayinDTO.getMedicalGroupLeaderCode() == null ? "" : prepayinDTO.getMedicalGroupLeaderCode());
        //医疗组组长名称
        thisIiPrepayin.setMedicalGroupLeaderName(prepayinDTO.getMedicalGroupLeaderName() == null ? "" : prepayinDTO.getMedicalGroupLeaderName());
        baseMapper.updateById(thisIiPrepayin);
        return ResultObject.successReturn("编辑成功!");
    }

    /**
     * 根据医生的编码获取手工录入的信息
     *
     * @param clinicCode 什么什么的编码
     * @return com.cw.common.api.ResultObject
     * @author ly
     * @date 2021/5/18 15:36
     */
    @Override
    public ResultObject getInsertIiPrepayinInsertSource(String clinicCode) {
        ThisIiPrepayin cardNo = baseDict2Mapper.getCardNoByRegisterTable(clinicCode);
        if (cardNo == null) {
            return ResultObject.errorReturn("暂未获取到此编码信息!!");
        }

        ThisIiPrepayin thisIiPrepayinByCardNo = baseDict2Mapper.getThisIiPrepayinByCardNo(cardNo.getCardNo());
        thisIiPrepayinByCardNo.setPaykindCode(cardNo.getPaykindCode());
        thisIiPrepayinByCardNo.setPactCode(cardNo.getPactCode());
        //通过病历号获取患者基本信息
        return ResultObject.successReturn(thisIiPrepayinByCardNo);
    }

    /**
     * 获取报表数据
     *
     * @param dataSourceRequest
     * @return
     */
    @Override
    public PageInfo<DataSourceResponse> getDataSource(DataSourceRequest dataSourceRequest) {
        PageHelper.startPage(dataSourceRequest.getPageNum(), dataSourceRequest.getPageSize());
        List<DataSourceResponse> dataSourceResponseList = baseMapper.getDataSource(dataSourceRequest);
        return new PageInfo<>(dataSourceResponseList);
    }


    /**
     * 获取上个月的第一天
     *
     * @return java.util.Date
     * @author ly
     * @date 2021/5/20 9:14
     */
    private Date getLastMonthStartDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取上个月的最后一天
     *
     * @return java.util.Date
     * @author ly
     * @date 2021/5/20 9:35
     */
    private Date getLastMonthLastDay() {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        return calendar.getTime();
    }

    @Override
    public void downDataSourceFormExcel(HttpServletResponse response, DataSourceRequest dataSourceRequest) throws IOException {

        List<DataSourceResponse> dataSourceResponseList = baseMapper.getDataSource(dataSourceRequest);
        String name = String.valueOf(System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
        EasyExcel.write(response.getOutputStream(), DataSourceResponse.class)
                .sheet("sheet")
                .doWrite(dataSourceResponseList);
    }

    /**
     * 住院登记记录
     *
     * @param condition 查询条件
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author ly
     * @date 2021/5/20 9:47
     */
    @Override
//    public Map<String, Object> getTheInpatientOfficeHasBeenProcessed(InpatientRegistrationCondition condition) {
//        Map<String, Object> resultMap = new HashMap<>(2);
//        String stayInBed = condition.getStayInBed();
//        if (!"1".equals(stayInBed)) {
//            condition.setStayInBed(null);
//        }
//
//        //门诊
//        Integer nullPorint = condition.getOutpatientPageNum();
//        if (ObjectUtil.isNotNull(nullPorint)) {
//            condition.setCode("1");
//            PageHelper.startPage(nullPorint, 15, false);
//            List<ThisIiPrepayin> thisIiPrepayins = baseMapper.getTheInpatientOfficeHasBeenProcessed(condition);
//            resultMap.put("outpatient", thisIiPrepayins);
//        }
//
//        //急诊
//        Integer nullPointCheck = condition.getEmergencyCallPageNum();
//        if (ObjectUtil.isNotNull(nullPointCheck)) {
//            condition.setCode("2");
//            PageHelper.startPage(nullPointCheck, 15, false);
//            List<ThisIiPrepayin> thisIiPrepayins = baseMapper.getTheInpatientOfficeHasBeenProcessed(condition);
//            resultMap.put("emergencyCall", thisIiPrepayins);
//        }
//        return resultMap;
//    }

    public Map<String, Object> getTheInpatientOfficeHasBeenProcessed(InpatientRegistrationCondition condition) {
        Map<String, Object> resultMap = new HashMap<>(2);
        String stayInBed = condition.getStayInBed();
        if (!"1".equals(stayInBed)) {
            condition.setStayInBed(null);
        }

        List<ThisIiPrepayin> thisIiPrepayins = baseMapper.getTheInpatientOfficeHasBeenProcessed(condition);
        //门诊
        List<ThisIiPrepayin> mzList = thisIiPrepayins.stream()
                .filter(t -> t.getRegisteCode() != null && !t.getRegisteCode().equals("6"))
                .collect(Collectors.toList());
        //急诊
        List<ThisIiPrepayin> jzList = thisIiPrepayins.stream()
                .filter(t -> t.getRegisteCode() != null && t.getRegisteCode().equals("6"))
                .collect(Collectors.toList());
        resultMap.put("outpatient", mzList);
        resultMap.put("emergencyCall", jzList);
        return resultMap;
    }

    /**
     * 更改状态为作废状态
     *
     * @param preId 预约记录号
     * @return boolean
     * @author ly
     * @date 2021/5/31 10:51
     */
    @Override
    public boolean updateState(Integer preId) {
        ThisIiPrepayin thisIiPrepayin = new ThisIiPrepayin();
        thisIiPrepayin.setPreid(BigDecimal.valueOf(preId));
        thisIiPrepayin.setPreState("9");
        return updateById(thisIiPrepayin);
    }

    /**
     * 出院列表
     *
     * @param condition 查询条件
     * @return java.lang.Map<java.lang.String, java.lang.Object>
     * @author ly
     * @date 2021/07/13 11:04
     */
    @Override
    @Deprecated
    public Map<String, Object> dischargeList(InpatientRegistrationCondition condition) {
        Map<String, Object> resultMap = new HashMap<>(2);
        //门诊
        Integer nullPorint = condition.getOutpatientPageNum();
        if (ObjectUtil.isNotNull(nullPorint)) {
            condition.setCode("1");
            PageHelper.startPage(nullPorint, 15, false);
            List<ThisIiPrepayin> thisIiPrepayins = baseMapper.getDischargeList(condition);
            resultMap.put("outpatient", thisIiPrepayins);
        }
        //急诊
        Integer nullPointCheck = condition.getEmergencyCallPageNum();
        if (ObjectUtil.isNotNull(nullPointCheck)) {
            condition.setCode("2");
            PageHelper.startPage(nullPointCheck, 15, false);
            List<ThisIiPrepayin> thisIiPrepayins = baseMapper.getDischargeList(condition);
            resultMap.put("emergencyCall", thisIiPrepayins);
        }
        return resultMap;
    }

    /**
     * 历史记录列表
     *
     * @param condition 查询条件
     * @return java.lang.Map<java.lang.String, java.lang.Object>
     * @author ly
     * @date 2021/07/19 14:27
     */
    @Override
    public Map<String, Object> historyRecord(InpatientRegistrationCondition condition) {
        Map<String, Object> resultMap = new HashMap<>(2);
        String stayInBed = condition.getStayInBed();

        //门诊
        Integer nullPorint = condition.getOutpatientPageNum();
        if (ObjectUtil.isNotNull(nullPorint)) {
            condition.setCode("1");
            PageHelper.startPage(nullPorint, 15, false);
            List<ThisIiPrepayin> thisIiPrepayins = baseMapper.getHistoryRecordList(condition);
            resultMap.put("outpatient", thisIiPrepayins);
        }

        //急诊
        Integer nullPointCheck = condition.getEmergencyCallPageNum();
        if (ObjectUtil.isNotNull(nullPointCheck)) {
            condition.setCode("2");
            PageHelper.startPage(nullPointCheck, 15, false);
            List<ThisIiPrepayin> thisIiPrepayins = baseMapper.getHistoryRecordList(condition);
            resultMap.put("emergencyCall", thisIiPrepayins);
        }
        return resultMap;
    }

    /**
     * 将电子住院证设置为取消状态
     *
     * @param preId 主键
     * @return java.lang.boolean
     * @author ly
     * @date 2021-09-07 10:20
     */
    @Override
    public boolean cancelIiprepayIn(String preId, String state) {
        if (StringUtil.isEmpty(preId)) {
            return false;
        }
        ThisIiPrepayin thisIiPrepayin = new ThisIiPrepayin();
        thisIiPrepayin.setPreid(new BigDecimal(preId));
        thisIiPrepayin.setPreState(state);
        return updateById(thisIiPrepayin);
    }

    @Override
    @Transactional
    public boolean changeBedType(List<CwglBedtypechange> ListInfo) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        ListInfo.forEach(info -> {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("gy_type", info.getAfterType());
            resultMap.put("IF_GY", info.getBeforeType());
            resultMap.put("as_dept_code", info.getDeptCode());
            resultMap.put("as_nurse_cell_code", info.getNurseCellCode());
            resultMap.put("as_bed_no", info.getBedNo());
            resultMap.put("v_result", 0);
            resultMap.put("v_ErrText", "");
            baseMapper.chageBedType(resultMap);
            if (!resultMap.get("v_result").toString().equals("-1")) {
                info.setCreatedOn(df.format(new Date()));
                info.setCreatedBy("俞秋兴");
                bedTypeMapper.save(info);
            }
        });
        return true;
    }

    @Override
    public boolean changeBedTypeByNurseCode(String nurseCode) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        List<HisCwglDept> deptList = deptMapper.getDeptList(new EmptyBedsRequest());
        List<HisCwglNurse> nurseList = nurseMapper.getWardList(null);
        LambdaQueryWrapper<IaSickbedinfo> queryWrapper = new LambdaQueryWrapper<>();
        if (nurseCode != null && !nurseCode.isEmpty()) {
            queryWrapper.eq(IaSickbedinfo::getNurseCellCode, nurseCode);
        }
        queryWrapper.eq(IaSickbedinfo::getIfGy, "1");//1
        queryWrapper.eq(IaSickbedinfo::getGyBack, "1");
//        queryWrapper.eq(IaSickbedinfo::getBedNo, "2941001145");//测试
        List<IaSickbedinfo> jgSickBedList = iaSickbedinfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(jgSickBedList)) {
            return true;
        }


        jgSickBedList.forEach(info -> {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("gy_type", 0);//0:从集管转非集管   1:从非集管转集管
            resultMap.put("IF_GY", 0);//0
            resultMap.put("as_dept_code", info.getDeptCode());
            resultMap.put("as_nurse_cell_code", info.getNurseCellCode());
            resultMap.put("as_bed_no", info.getBedNo());
            resultMap.put("v_result", 0);
            resultMap.put("v_ErrText", "");
            baseMapper.chageBedType(resultMap);

            HisCwglDept matchDept = deptList.stream()
                    .filter(t -> t.getDeptCode().equals(info.getDeptCode()))
                    .findFirst()
                    .orElse(null);
            HisCwglNurse matchNurse = nurseList.stream()
                    .filter(t -> t.getDeptCode().equals(info.getNurseCellCode()))
                    .findFirst()
                    .orElse(null);
            CwglBedtypechange changeInfo = new CwglBedtypechange();
            changeInfo.setBedNo(info.getBedNo());
            changeInfo.setDeptCode(info.getDeptCode());
            if (matchDept != null) {
                changeInfo.setDeptName(matchDept.getDeptName());
            } else {
                changeInfo.setDeptName("");
            }
            changeInfo.setNurseCellCode(info.getNurseCellCode());
            if (matchNurse != null) {
                changeInfo.setNurseCellName(matchNurse.getDeptName());
            } else {
                changeInfo.setNurseCellName("");
            }
            changeInfo.setOperId("101468");
            changeInfo.setCreatedBy("俞秋兴"); // 还原人
            changeInfo.setOperReason("特殊时段,统一修改");
            changeInfo.setBeforeType(info.getGyBack());
            changeInfo.setAfterType("0");
            changeInfo.setCreatedOn(df.format(new Date()));
            changeInfo.setRemark("批量还原操作");
            if (!resultMap.get("v_result").toString().equals("-1")) {
                bedTypeMapper.save(changeInfo);
            }
        });
        return true;
    }

    /**
     * easyExcel 表格导出样式
     *
     * @return
     */
    public static HorizontalCellStyleStrategy style() {
        // 头的样式
        WriteCellStyle headStyle = new WriteCellStyle();
        headStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        //设置颜色不填充
        headStyle.setFillPatternType(FillPatternType.NO_FILL);
        WriteFont headFont = new WriteFont();
        //字体加粗
        headFont.setBold(true);
        headFont.setFontHeightInPoints((short) 11);
        headStyle.setWriteFont(headFont);
        headStyle.setWrapped(true);
        headStyle.setBorderBottom(BorderStyle.MEDIUM);
        headStyle.setBorderTop(BorderStyle.MEDIUM);
        headStyle.setBorderLeft(BorderStyle.NONE);
        headStyle.setBorderRight(BorderStyle.NONE);

        // 内容的样式/
        WriteCellStyle contentStyle = new WriteCellStyle();
        //填充颜色
//        contentStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//        contentStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontName("宋体");
        contentWriteFont.setFontHeightInPoints((short) 11);
        contentStyle.setWriteFont(contentWriteFont);
//        contentStyle.setBorderTop(BorderStyle.THIN);
//        contentStyle.setBorderBottom(BorderStyle.THIN);
//        contentStyle.setBorderLeft(BorderStyle.THIN);
//        contentStyle.setBorderRight(BorderStyle.THIN);
        //水平居中
        contentStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        //垂直居中
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentStyle.setWrapped(false);
        return new HorizontalCellStyleStrategy(headStyle, contentStyle);
    }

//    private List<ThisIiPrepayin> getFinishYQ(List<ThisIiPrepayin> yqList) {
//        List<ThisIiPrepayin> finishList = new ArrayList<>();
//        try {
//            //获取cardNo 与院前记录进行匹配
//            List<String> cardNoList = yqList.stream().map(t -> t.getCardNo()).collect(Collectors.toList());
//            // 科室编码
//            VYqBrdjxxConditionRequest deptcode = new VYqBrdjxxConditionRequest();
//            List<ReportReadyDocNameDTO> reportReadyDocNames = IVYqBrdjxxMapper.getReportList(deptcode);
//            if (!CollectionUtils.isEmpty(reportReadyDocNames)) {
//                List<ReportReadyDocNameDTO> filterList = reportReadyDocNames.stream().filter(t -> cardNoList
//                .contains(t.getMcardNo())).collect(Collectors.toList());
//                for (ReportReadyDocNameDTO reportReadyDocNameDTO : filterList) {
//                    //诊断号
//                    String clinicCode = reportReadyDocNameDTO.getClinicCode();
//
//                    /*检验进度判断*/
//                    //检验列表
//                    List<LJysqdxx> lJysqdxxsByDorctrequestno = ilJysqdxxService.getLJysqdxxsByDorctrequestno
//                    (clinicCode);
//                    if (lJysqdxxsByDorctrequestno == null) {
//                        continue;
//                    }
//                    //获取检验完成度
//                    List<String> doctrequestnos = lJysqdxxsByDorctrequestno.stream().map
//                    (LJysqdxx::getDoctrequestno).collect(Collectors.toList());
//                    if (doctrequestnos == null) {
//                        continue;
//                    }
//                    //拿到ZTID编码集合
//                    List<LJysqdxxXmmx> lJysqdxxXmmxByDoctrequestnos = new ArrayList<>();
//                    for (int i = 0; i < doctrequestnos.size(); i++) {
//                        List<LJysqdxxXmmx> searchList = ilJysqdxxXmmxService.getLJysqdxxXmmxByDoctrequestnos
//                        (doctrequestnos.get(i));
//                        if (CollectionUtils.isNotEmpty(searchList)) {
//                            lJysqdxxXmmxByDoctrequestnos.addAll(searchList);
//                        }
//                    }
//                    if (lJysqdxxXmmxByDoctrequestnos == null) {
//                        continue;
//                    }
//                    lJysqdxxXmmxByDoctrequestnos = lJysqdxxXmmxByDoctrequestnos.stream().distinct().collect
//                    (Collectors.toList());
//                    Map<String, List<String>> ljytmxxByExaminaimCode = ilJytmxxService.getLjytmxxByExaminaimCode
//                    (lJysqdxxXmmxByDoctrequestnos, clinicCode);
//                    if (ljytmxxByExaminaimCode == null) {
//                        continue;
//                    }
//                    List<String> doItList = ljytmxxByExaminaimCode.get("doIt");
//                    if (doItList == null || doItList.size() != lJysqdxxXmmxByDoctrequestnos.size()) {
//                        continue;
//                    }
//
//
////                    //已检查集合
////                    List<String> erApplyItemOutsDoIt = reportReadyDocNameDTO.getErApplyItemOutsDoIt();
////                    //未检查集合
////                    List<String> erApplyItemOutsNotDoIt = reportReadyDocNameDTO.getErApplyItemOutsNotDoIt();
////                    if (erApplyItemOutsDoIt == null || erApplyItemOutsNotDoIt == null || !(erApplyItemOutsDoIt
// .size() == erApplyItemOutsNotDoIt.size())) {
////                        continue;
////                    }
//                    /*检查进度判断*/
//                    if (reportReadyDocNameDTO.getInspectProgress().isEmpty()) {
//                        continue;
//                    } else {
//                        List<String> inspectProcess = Arrays.asList(reportReadyDocNameDTO.getInspectProgress()
//                        .split("/"));
//                        if (inspectProcess.size() != 2) {
//                            continue;
//                        }
//                        if (!inspectProcess.get(0).equals(inspectProcess.get(1))) {
//                            continue;
//                        }
//                    }
//
//                    ThisIiPrepayin match = yqList.stream().filter(t -> t.getCardNo().equals(reportReadyDocNameDTO
//                    .getMcardNo())).findFirst().orElse(null);
//                    finishList.add(match);
//                }
//            }
//        } catch (Exception ex) {
//            int a = 0;
//        }
//
//
//        return finishList;
//    }


    private List<ThisIiPrepayin> getFinishYQ(List<ThisIiPrepayin> yqList) {
        List<ThisIiPrepayin> finishList = new ArrayList<>();
        try {
            //获取cardNo 与院前记录进行匹配
            List<String> cardNoList = yqList.stream().map(t -> t.getCardNo()).collect(Collectors.toList());
            // 科室编码
            VYqBrdjxxConditionRequest deptcode = new VYqBrdjxxConditionRequest();
            List<ReportReadyDocNameDTO> reportReadyDocNames = ivYqBrdjxxService.getReportList(deptcode);
            if (!CollectionUtils.isEmpty(reportReadyDocNames)) {
                List<ReportReadyDocNameDTO> filterList = reportReadyDocNames.stream()
                        .filter(t -> cardNoList.contains(t.getMcardNo()))
                        .collect(Collectors.toList());

                List<String> clinicCodeList = reportReadyDocNames.stream()
                        .map(ReportReadyDocNameDTO::getClinicCode)
                        .collect(Collectors.toList());
                // 获取相应的诊断号的LJysqdxx集合
                LambdaQueryWrapper<LJysqdxx> lJysqdxxQueryWrapper = new LambdaQueryWrapper<>();
                lJysqdxxQueryWrapper.in(LJysqdxx::getPatientno, clinicCodeList);
                List<LJysqdxx> lJysqdxxList = lJysqdxxMapper.selectList(lJysqdxxQueryWrapper);
                // 获取lJysqdxxList中所有的doctrequestno形成集合
                List<String> doctRequestNoList = lJysqdxxList.stream()
                        .map(LJysqdxx::getDoctrequestno)
                        .collect(Collectors.toList());
                // 获取另一个比对列表，提前放到jvm内存
                LambdaQueryWrapper<LJytmxx> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.select(LJytmxx::getExaminaim,
                        LJytmxx::getExaminaimcode,
                        LJytmxx::getDoctrequestno,
                        LJytmxx::getReceivetime,
                        LJytmxx::getExecutetime,
                        LJytmxx::getChecktime,
                        LJytmxx::getSampleno);
                queryWrapper.in(LJytmxx::getDoctrequestno, doctRequestNoList);
                List<LJytmxx> lJytmxxList = ilJytmxxService.list(queryWrapper);

                for (ReportReadyDocNameDTO reportReadyDocNameDTO : filterList) {
                    //诊断号
                    String clinicCode = reportReadyDocNameDTO.getClinicCode();

                    /*检验进度判断*/
                    //检验列表
//                    List<LJysqdxx> lJysqdxxsByDorctrequestno = ilJysqdxxService.getLJysqdxxsByDorctrequestno
//                    (clinicCode);
                    List<LJysqdxx> lJysqdxxsByDorctrequestno = new ArrayList<>();
                    List<LJysqdxx> lJysqdxxListByClineCode = lJysqdxxList.stream()
                            .filter(t -> t.getPatientno().equals(clinicCode))
                            .collect(Collectors.toList());
                    for (LJysqdxx lJysqdxx : lJysqdxxListByClineCode) {
                        List<LJytmxx> collect = lJytmxxList.stream()
                                .filter(t -> t.getDoctrequestno().equals(lJysqdxx.getDoctrequestno()))
                                .collect(Collectors.toList());
                        lJysqdxx.setLJysqdxxXmmxList(collect);
                        lJysqdxxsByDorctrequestno.add(lJysqdxx);
                    }
                    if (lJysqdxxsByDorctrequestno == null) {
                        continue;
                    }
                    //获取检验完成度
                    List<String> doctrequestnos = lJysqdxxsByDorctrequestno.stream()
                            .map(LJysqdxx::getDoctrequestno)
                            .collect(Collectors.toList());
                    if (doctrequestnos == null) {
                        continue;
                    }

//                    List<LJysqdxxXmmx> lJysqdxxXmmxsByZtId2 = lJysqdxxXmmxMapper.getLJysqdxxXmmxsByZtId2
//                    (doctrequestnos);
                    //拿到ZTID编码集合
                    List<LJysqdxxXmmx> lJysqdxxXmmxByDoctrequestnos = new ArrayList<>();
                    for (int i = 0; i < doctrequestnos.size(); i++) {
                        List<LJysqdxxXmmx> searchList = ilJysqdxxXmmxService.getLJysqdxxXmmxByDoctrequestnos(
                                doctrequestnos.get(i));
//                        String doctrequestno = doctrequestnos.get(i);
//                        List<LJysqdxxXmmx> searchList = lJysqdxxXmmxsByZtId2.stream().filter(t -> t
//                        .getDoctrequestno().equals(doctrequestno)).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(searchList)) {
                            lJysqdxxXmmxByDoctrequestnos.addAll(searchList);
                        }
                    }
                    if (lJysqdxxXmmxByDoctrequestnos == null) {
                        continue;
                    }
                    lJysqdxxXmmxByDoctrequestnos = lJysqdxxXmmxByDoctrequestnos.stream()
                            .distinct()
                            .collect(Collectors.toList());
                    Map<String, List<String>> ljytmxxByExaminaimCode = ilJytmxxService.getLjytmxxByExaminaimCode(
                            lJysqdxxXmmxByDoctrequestnos,
                            clinicCode);
                    if (ljytmxxByExaminaimCode == null) {
                        continue;
                    }
                    List<String> doItList = ljytmxxByExaminaimCode.get("doIt");
                    if (doItList == null || doItList.size() != lJysqdxxXmmxByDoctrequestnos.size()) {
                        continue;
                    }

                    /*检查进度判断*/
                    if (reportReadyDocNameDTO.getInspectProgress().isEmpty()) {
                        continue;
                    } else {
                        List<String> inspectProcess = Arrays.asList(reportReadyDocNameDTO.getInspectProgress()
                                .split("/"));
                        if (inspectProcess.size() != 2) {
                            continue;
                        }
                        if (!inspectProcess.get(0).equals(inspectProcess.get(1))) {
                            continue;
                        }
                    }

                    ThisIiPrepayin match = yqList.stream()
                            .filter(t -> t.getCardNo().equals(reportReadyDocNameDTO.getMcardNo()))
                            .findFirst()
                            .orElse(null);
                    finishList.add(match);
                }
            }
        } catch (Exception ex) {
            int a = 0;
        }
        return finishList;
    }

    /**
     * 床位类型转换查询
     * xnd
     *
     * @return
     */
    @Override
    public PageInfo<CwglBedtypechange> selectCwInformation(BedChangeTypeRequest request) {
        List<CwglBedtypechange> filterNew = new ArrayList<>();
        //先查所有的人
        List<CwglBedtypechange> cwglBedtypechanges = bedtypechangeMapper.selectCwInformation();
        //床位号去分组
        Map<String, List<CwglBedtypechange>> groupHY = cwglBedtypechanges.stream()
                .collect(Collectors.groupingBy(CwglBedtypechange::getBedNo));
        Iterator<String> it = groupHY.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            List<CwglBedtypechange> collectDate = groupHY.get(key);
            CwglBedtypechange cwglBedtypechange = collectDate.stream()
                    .max(Comparator.comparing(CwglBedtypechange::getCreatedOn))
                    .orElse(null);
            if (cwglBedtypechange != null && cwglBedtypechange.getAfterType().equals("0")) {
                filterNew.add(cwglBedtypechange);
            }

        }

        return PageHelperTool.excutePageInfo(filterNew, request.getPageIndex(), request.getPageSize());
    }

    @Override
    public ResultObject releaseJGBedHistory(ReleaseJGBedHistoryDTO releaseJGBedHistoryDTO) {
        try {
            ThisIiPrepayin searchResult = thisIiPrepayinMapper.getReleaseBedHistoryInfo(releaseJGBedHistoryDTO);
            if (searchResult != null) {
                List<BigDecimal> lstPreid = new ArrayList<>();
                lstPreid.add(searchResult.getPreid());

                thisIiPrepayinMapper.updateBedNo(lstPreid);
                patientBedMiddleMapper.updateReleaseBed(lstPreid);
            } else {
                return ResultObject.errorReturn("未找到该患者信息,请联系管理员");
            }
        } catch (Exception ex) {
            return ResultObject.errorReturn("释放出错,请联系管理员");
        }

        return ResultObject.errorReturn("释放成功,请刷新页面");
    }

    @Override
    public ResultObject getThisIiPrepayinByPreid(BigDecimal preid) {
        LambdaQueryWrapper<ThisIiPrepayin> lw = new LambdaQueryWrapper<>();
        lw.eq(ThisIiPrepayin::getPreid, preid);
        return ResultObject.successReturn(list(lw).stream().findFirst());
    }

    @Override
    public List<LeaveAdviceVO> leaveAdvicePage(LeaveAdviceDTO dto) {
        List<LeaveAdviceVO> leaveAdviceVOS = thisIiPrepayinMapper.leaveAdvicePage(dto);
        if (leaveAdviceVOS.isEmpty()) {
            return new ArrayList<>();
        }
        return leaveAdviceVOS;
    }

    @Override
    public List<PreoperationListVO> preoperation(PreoperationDTO dto) {
        List<PreoperationListVO> preoperation = thisIiPrepayinMapper.preoperation(dto);
        return preoperation;
    }

    @Override
    public List<MedicalGroupVO> getmedicalGroupLeader(String medicalGroupCode, String deptCode) {
        return thisIiPrepayinMapper.getmedicalGroupLeader(medicalGroupCode,deptCode);
    }

    @Override
    public ResultObject getReadmissionDays(String idenNo,Date predate) {
        List<ReadmissionDaysVO> readmissionDays = thisIiPrepayinMapper.getReadmissionDays(idenNo,predate);
        if(CollectionUtils.isEmpty(readmissionDays))
        {
            return ResultObject.successReturn(true);
        }
        String patten ="患者{0}，在我院{1}{2}办理出院，出院诊断{3}，是否继续开住院证?";
        ReadmissionDaysVO maxRecord = readmissionDays.stream()
                .max(Comparator.comparingInt(ReadmissionDaysVO::getDiffdays))
                .orElse(null);
        String formattedString = MessageFormat.format(patten,maxRecord.getName(),maxRecord.getDeptName(),maxRecord.getPaykindCode(),maxRecord.getDiagName());
        return ResultObject.successReturn(formattedString);
    }

    @Override
    public List<MedicalGroupVO> getmedicalGroup(String deptCode) {
        return thisIiPrepayinMapper.getmedicalGroup(deptCode);
    }
}
